# -*- coding: utf-8 -*-
'''
@文件    :oss.py
@说明    :对象存储服务(Object Storage Service)
@时间    :2024/12/12 11:25:17
@作者    :浪晋
@版本    :1.0
'''
import oss2


class AliOss(object):
    def __init__(self, secretId, secretKey, bucket, region):
        self.secretId = secretId
        self.secretKey = secretKey
        self.bucket = bucket        # 例如 :heimerclin
        self.region = region    # 例如: oss-cn-chengdu
        self.endpoint = f"https://{self.region}.aliyuncs.com"  # 例如: https://cos.ap-chengdu.myqcloud.com

    def get_oss_client(self):
        auth = oss2.Auth(self.secretId, self.secretKey)
        client = oss2.Bucket(auth, self.endpoint, self.bucket)
        return client

    def put_object(self, key: str, data):
        """文件流/字节流上传"""
        client = self.get_oss_client()
        response = client.put_object(key, data)
        url = f"https://{self.bucket}.{self.region}.aliyuncs.com/{key}"
        return url
    

    def put_local_file(self,key: str, path: str):
        """本地文件上传"""
        client = self.get_oss_client()
        response = client.put_object_from_file(key, path)
        url = f"https://{self.bucket}.{self.region}.aliyuncs.com/{key}"
        return url